package com.boot.demojdbctemplate.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JDBCTemplate extends org.springframework.jdbc.core.JdbcTemplate {
    @Autowired
    public JDBCTemplate(DataSource dataSource) {
        super(dataSource);
    }

    private final static Map<Class, BeanPropertyRowMapper > clzCache = new HashMap();

    private <T> BeanPropertyRowMapper getBeanInstance(Class<T> clz) {
        if (clzCache.containsKey(clz)) {
            return clzCache.get(clz);
        } else {
            BeanPropertyRowMapper<T> rowMapper = new BeanPropertyRowMapper<>(clz);
            clzCache.put(clz, rowMapper);
            return rowMapper;
        }

    }


    public <T> List<T> getList(String sql, Class<T> clz)  {
        return super.query(sql, getBeanInstance(clz));
    }

    public <T> T getObject(String sql, Class<T> clz)   {
        return super.queryForObject(sql, (RowMapper<T>) getBeanInstance(clz));
    }
}
